import Vue from 'vue'
import Router from 'vue-router'
import constantJs from '../assets/js/constant'

Vue.use(Router)
// 解决报错 此方法只针对VueRouter3.0以上
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new Router({
  //mode: 'history',
  mode: 'hash',
  routes: [
    { path: '/', redirect: 'index' },
    { path: '/login', name: 'login', meta: {title: '登录'}, component: () => import('@/view/Login.vue') },
    { path: '/home',
      name: 'home',
      meta: {title: '首页'},
      component: () => import('@/view/Home.vue'),
      redirect: '/index',
      children: [
        { path: '/index', name: 'index', meta: {title: '主页'}, component: () => import('@/view/Index.vue') },
        { path: '/ns', name: 'ns', meta: {title: '命名空间'}, component: () => import('@/view/ns/Ns.vue') },
        { path: '/ds', name: 'ds', meta: {title: '数据源管理'}, component: () => import('@/view/ds/Ds.vue') },
        { path: '/mapper', name: 'mapper', meta: {title: 'Mapper管理'}, component: () => import('@/view/mapper/Mapper.vue') },
        { path: '/mapper/sql', name: 'mapper-sql', meta: {title: 'SQL管理'}, component: () => import('@/view/sql/Sql.vue') },
        { path: '/sql/log', name: 'sql-log', meta: {title: '日志管理'}, component: () => import('@/view/sql/Log.vue') },
        { path: '/template', name: 'template', meta: {title: '模板管理'}, component: () => import('@/view/template/Template.vue') },
        { path: '/generator', name: 'generator', meta: {title: '代码生成器'}, component: () => import('@/view/generator/Generator.vue') },
        { path: '/sys/db', name: 'sys', meta: {title: '数据库配置'}, component: () => import('@/view/sys/DbConfig.vue') },
        { path: '/user', name: 'user', meta: {title: '用户管理'}, component: () => import('@/view/user/User.vue') }
      ]
    }
  ]
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
// 修改页面 title
  if (to.meta.title) {
    document.title = Vue.prototype.$constant.name + '-' + to.meta.title
  }
  // 放行登录页面
  if (to.path === '/login') {
    return next()
  }
  // 非登录页面拦截跳转登录页面
  const token = localStorage.getItem(constantJs.authTokenHeader)
  if (!token || token === 'undefined') {
    return next('/login')
  } else {
    next()
  }
  return next()
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
// router.afterEach((to,from)=>{
//   if(this.a && this.a.app && this.a.app.$store.state.activePath !== to.path){
//     this.a.app.$store.dispatch('changeActivePath', to.path)
//   }
// })

export default router
